package com.op.teachingliteapp.sender.runnable;

import android.util.Log;
import android.widget.ArrayAdapter;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

import com.op.teachingliteapp.sender.Constants;
import com.op.teachingliteapp.sender.handler.DeviceScanHandler;


/**
 * Created by Genji on 2015/5/16.
 */
public class DeviceScanRunnable implements Runnable {
    private ArrayAdapter adapter;
    private int deviceScanPort;

    public DeviceScanRunnable(ArrayAdapter adapter) {
        this.adapter = adapter;
        this.deviceScanPort = Constants.deviceScanPort;
    }

    public DeviceScanRunnable(ArrayAdapter adapter, int deviceScanPort) {

        this.adapter = adapter;
        this.deviceScanPort = deviceScanPort;
    }

    @Override
    public void run() {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true).handler(new DeviceScanHandler(adapter));
            Channel channel = bootstrap.bind(0).sync().channel();
            DatagramPacket datagramPacket =new DatagramPacket(Unpooled.copiedBuffer("is reciver ?", CharsetUtil.UTF_8),new InetSocketAddress("255.255.255.255",Constants.deviceScanPort));
            channel.writeAndFlush(datagramPacket).sync();
            if (!channel.closeFuture().await(15000)) {
                Log.i("connect time out","15s");
            }


        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();

        }

    }
}
